import { Component, Vue, PropSync } from 'vue-property-decorator';
import { Modal, Form, Input } from 'ant-design-vue'
import { CryptUtil } from '@/utils/CryptUtil';

const mediumRegex = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,}).");
const strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})");

@Component({
  components: {
    'a-modal': Modal,
    'a-input': Input,
    'a-form': Form,
    'a-form-item': Form.Item
  }
})
export default class ChangePassword extends Vue {
  @PropSync('_visible', {
    default: false
  })
  visible!: boolean;
  /** 用户信息 */
  userInfo: any = {};
  /** 是否为严格模式 */
  strictMode: any = 0;
  /** 是否能点击确定 */
  canClick: boolean = false;
  /** 表单 */
  form: any;
  /** 密码强度等级 */
  passwordLevel: string = "";
  /** 是否校验二次输入密码 */
  confirmDirty: boolean = false;

  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'changePassword' });
  }

  created() {
    this.getUserInfo();
  }

  async getUserInfo() {
    this.userInfo = await Vue.prototype.$axios.get('/system/api/humaninfo/profile');
    this.strictMode = await Vue.prototype.$axios.get('/system/api/static/security');
    this.canClick = true;
  }

  handleConfirmBlur(e: any) {
    const value = e.target.value;
    this.confirmDirty = this.confirmDirty || !!value;
  }

  validateToNextPassword(rule: any, value: string, callback: Function) {
    const form = this.form;
    if (value) {
      const medium = mediumRegex.test(value);
      const strong = strongRegex.test(value);
      if (!medium) {
        this.passwordLevel = "弱";
      } else if (medium && !strong) {
        this.passwordLevel = "中";
      } else if (strong) {
        this.passwordLevel = "强";
      }
    } else {
      this.passwordLevel = "";
    }
    if (value && this.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    if (this.strictMode === 1) {
      if (value.length <= 8) {
        return callback("使用8位以上的密码进行口令设置");
      } else {
        let testPassword = /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)(?=.*?[!#@*&.])[a-zA-Z\d!#@*&.]*$/;
        if (!testPassword.test(value)) {
          return callback('密码需包含数字、符号（!#@*&.）及大小写字母');
        }
      }
    } else {
      callback();
    }
  }

  compareToFirstPassword(rule: any, value: string, callback: Function) {
    const form = this.form;
    if (value && value !== form.getFieldValue('newPassword')) {
      callback('两次输入的密码不一致');
    } else {
      callback();
    }
  }

  onOk() {
    if (!this.canClick) return;
    this.form.validateFields().then(async (data: any) => {
      const { password, newPassword, confirm } = data;
      const params = {
        ...this.userInfo,
        password: CryptUtil.desEncrypt(password),
        newPassword: CryptUtil.desEncrypt(newPassword),
        passwordConfirm: CryptUtil.desEncrypt(confirm)
      };
      const result = await Vue.prototype.$axios.post('/system/api/humaninfo/changePassword', params);
      const keys = Object.keys(result);
      if (!result || (typeof result === 'object' && keys.length === 0)) {
        this.$message.error('旧密码输入错误！');
      } else {
        this.$message.success('密码修改成功！');
        this.visible = false;
      }
    }).catch(() => { });
  }
}